# 文件说明:
# removeCsvHeader.py - Removes the header from all CSV files in the current working directory

import csv
import shutil
import pathlib

# assign the path of source and destination folder
srcPath='D:/GITEE/study_code/removeCsvHeader'
destPath='D:/GITEE/study_code/headerRemoved'

# 创建文件夹变量
withHeaderPath=pathlib.Path(srcPath)
withoutHeaderPath=pathlib.Path(destPath)

# copy original folder or files
# shutil的函数形参要求是字符串
if not withoutHeaderPath.exists():
    shutil.copytree(srcPath,destPath)# 前者是源文件夹路径,后者是目标文件夹路径
else:
    for f in [x for x in withHeaderPath.iterdir() if x.is_file]:
        shutil.copy(str(f),destPath)# 前者是源文件路径,后者是目标文件夹路径

# Loop through every file in the current working directory.
# csvFilename是一个文件变量
for csvFilename in withoutHeaderPath.iterdir():
    if not csvFilename.name.endswith('.csv'):
        continue # skip  non-csv files
    
    print('Removing header from '+csvFilename.name+'……')

    # Read the CSV file in (skipping first row).
    csvRows=[]
    csvFileObj=open(csvFilename)
    readerFileObj=csv.reader(csvFileObj)
    for row in readerFileObj:
        if readerFileObj.line_num==1:
            continue # skip first row
        csvRows.append(row)
    csvFileObj.close()

    # Write out the CSV file.
    csvFileObj=open(csvFilename,'w')
    csvWriter=csv.writer(csvFileObj)
    for row in csvRows:
        csvWriter.writerow(row)
    csvFileObj.close()